// 初始化GoJS图表
let myDiagram;

function init() {
    const $ = go.GraphObject.make;
    
    // 设置 GoJS 许可证（用于移除水印）
    // 注意：这只是尝试，免费版本仍会显示水印
    if (typeof go !== 'undefined' && go.licenseKey !== undefined) {
        go.licenseKey = "";
    }

    myDiagram = $(go.Diagram, "myDiagramDiv", {
        "undoManager.isEnabled": true,
        layout: $(go.ForceDirectedLayout, {
            defaultSpringLength: 100,
            defaultElectricalCharge: 150,
            maxIterations: 200
        }),
        "toolManager.hoverDelay": 100,
        initialContentAlignment: go.Spot.Center,
        "animationManager.isEnabled": false
    });

    // 定义实体节点模板（矩形）
    myDiagram.nodeTemplateMap.add("Entity",
        $(go.Node, "Auto",
            {
                locationSpot: go.Spot.Center,
                selectionAdorned: true,
                resizable: false,
                layoutConditions: go.Part.LayoutStandard & ~go.Part.LayoutNodeSized
            },
            new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify),
            $(go.Shape, "Rectangle",
                {
                    fill: "#E3F2FD",
                    stroke: "#1976D2",
                    strokeWidth: 2,
                    minSize: new go.Size(80, 40)
                },
                new go.Binding("fill", "isHighlighted", function(h) {
                    return h ? "#BBDEFB" : "#E3F2FD";
                }).ofObject()
            ),
            $(go.TextBlock,
                {
                    margin: 12,
                    stroke: "#1976D2",
                    font: "bold 16px Inter, Microsoft YaHei",
                    textAlign: "center",
                    maxSize: new go.Size(120, NaN),
                    wrap: go.TextBlock.WrapFit
                },
                new go.Binding("text", "text")
            )
        )
    );

    // 定义属性节点模板（椭圆）
    myDiagram.nodeTemplateMap.add("Attribute",
        $(go.Node, "Auto",
            {
                locationSpot: go.Spot.Center,
                selectionAdorned: true,
                resizable: false,
                layoutConditions: go.Part.LayoutStandard & ~go.Part.LayoutNodeSized
            },
            new go.Binding("location", "loc", go.Point.parse).makeTwoWay(go.Point.stringify),
            $(go.Shape, "Ellipse",
                {
                    fill: "#FFF3E0",
                    stroke: "#F57C00",
                    strokeWidth: 2,
                    minSize: new go.Size(70, 35)
                },
                new go.Binding("fill", "isHighlighted", function(h) {
                    return h ? "#FFE0B2" : "#FFF3E0";
                }).ofObject()
            ),
            $(go.TextBlock,
                {
                    margin: 8,
                    stroke: "#F57C00",
                    font: "14px Inter, Microsoft YaHei",
                    textAlign: "center",
                    maxSize: new go.Size(100, NaN),
                    wrap: go.TextBlock.WrapFit
                },
                new go.Binding("text", "text")
            )
        )
    );

    // 定义连接线模板
    myDiagram.linkTemplate =
        $(go.Link,
            {
                routing: go.Link.Normal,
                curve: go.Link.None,
                corner: 0,
                toShortLength: 0,
                fromShortLength: 0,
                relinkableFrom: true,
                relinkableTo: true,
                reshapable: true,
                resegmentable: true,
                mouseEnter: function(e, link) {
                    link.findObject("HIGHLIGHT").stroke = "#F57C00";
                },
                mouseLeave: function(e, link) {
                    link.findObject("HIGHLIGHT").stroke = "#666";
                }
            },
            new go.Binding("points").makeTwoWay(),
            $(go.Shape,
                {
                    isPanelMain: true,
                    strokeWidth: 2,
                    stroke: "#666"
                },
                new go.Binding("stroke", "isSelected", function(sel) {
                    return sel ? "#F57C00" : "#666";
                }).ofObject()
            ),
            $(go.Shape,
                {
                    name: "HIGHLIGHT",
                    isPanelMain: true,
                    strokeWidth: 3,
                    stroke: "transparent"
                }
            )
        );

    // 设置默认的节点和连接数据
    myDiagram.model = new go.GraphLinksModel([], []);
    
    // 监听模型变化，更新状态信息
    myDiagram.addModelChangedListener(function(evt) {
        updateStatusInfo();
    });
    
    // 移除 GoJS 水印
    removeGoJSWatermark();
}

// 移除 GoJS 水印的函数
function removeGoJSWatermark() {
    // 延迟执行以确保 DOM 已渲染
    setTimeout(() => {
        const diagramDiv = document.getElementById('myDiagramDiv');
        if (diagramDiv) {
            // 方法1: 查找并移除包含 GoJS 文本的元素
            const allDivs = diagramDiv.querySelectorAll('div');
            allDivs.forEach(div => {
                const text = div.textContent || div.innerText;
                if (text && (text.includes('GoJS') || text.includes('gojs'))) {
                    div.style.display = 'none';
                    div.style.visibility = 'hidden';
                    div.style.opacity = '0';
                }
            });
            
            // 方法2: 查找小字体的绝对定位元素
            const smallTexts = diagramDiv.querySelectorAll('div[style*="position: absolute"]');
            smallTexts.forEach(text => {
                const style = text.getAttribute('style') || '';
                const fontSize = style.match(/font-size:\s*(\d+)px/);
                if (fontSize && parseInt(fontSize[1]) <= 10) {
                    text.style.display = 'none';
                }
            });
            
            // 方法3: 查找特定样式的水印元素
            const watermarkSelectors = [
                'div[style*="font-family: sans-serif"]',
                'div[style*="font-size: 9px"]',
                'div[style*="color: gray"]',
                'div[style*="color: grey"]'
            ];
            
            watermarkSelectors.forEach(selector => {
                const elements = diagramDiv.querySelectorAll(selector);
                elements.forEach(el => {
                    const text = el.textContent || el.innerText;
                    if (text && text.length < 50) { // 水印通常是短文本
                        el.style.display = 'none';
                    }
                });
            });
            
            // 方法4: 使用 MutationObserver 监听新添加的元素
            if (!diagramDiv.hasAttribute('data-watermark-observer')) {
                diagramDiv.setAttribute('data-watermark-observer', 'true');
                
                const observer = new MutationObserver((mutations) => {
                    mutations.forEach((mutation) => {
                        mutation.addedNodes.forEach((node) => {
                            if (node.nodeType === 1 && node.tagName === 'DIV') {
                                const text = node.textContent || node.innerText;
                                const style = node.getAttribute('style') || '';
                                
                                // 检查是否为水印
                                if ((text && (text.includes('GoJS') || text.includes('gojs'))) ||
                                    (style.includes('font-size: 9px')) ||
                                    (style.includes('position: absolute') && text && text.length < 50)) {
                                    node.style.display = 'none';
                                    node.style.visibility = 'hidden';
                                    node.style.opacity = '0';
                                }
                            }
                        });
                    });
                });
                
                observer.observe(diagramDiv, {
                    childList: true,
                    subtree: true,
                    attributes: false,
                    characterData: false
                });
            }
        }
    }, 100);
    
    // 再次延迟执行，确保所有异步渲染完成
    setTimeout(() => {
        removeWatermarkElements();
    }, 500);
}

// 辅助函数：移除水印元素
function removeWatermarkElements() {
    const diagramDiv = document.getElementById('myDiagramDiv');
    if (diagramDiv) {
        // 查找所有可能的水印元素
        const allElements = diagramDiv.querySelectorAll('*');
        allElements.forEach(el => {
            const text = el.textContent || el.innerText || '';
            const computedStyle = window.getComputedStyle(el);
            
            // 检查是否为水印特征
            if (text.toLowerCase().includes('gojs') ||
                (computedStyle.fontSize === '9px' && computedStyle.position === 'absolute') ||
                (text.length < 20 && computedStyle.color === 'rgb(128, 128, 128)')) {
                el.style.display = 'none !important';
                el.style.visibility = 'hidden !important';
                el.style.opacity = '0 !important';
            }
        });
    }
}

// 解析输入文本并生成图表数据
function parseInput(text) {
    const lines = text.split('\n').filter(line => line.trim() !== '');
    const nodes = [];
    const links = [];
    let currentEntity = null;
    let nodeId = 0;

    lines.forEach(line => {
        const trimmedLine = line.trim();
        if (trimmedLine === '') return;

        // 检查是否为实体（顶格输入）
        if (!line.startsWith(' ') && !line.startsWith('\t')) {
            // 这是一个实体
            currentEntity = {
                key: nodeId++,
                text: trimmedLine,
                category: "Entity"
            };
            nodes.push(currentEntity);
        } else if (currentEntity) {
            // 这是一个属性（有缩进）
            const attribute = {
                key: nodeId++,
                text: trimmedLine,
                category: "Attribute"
            };
            nodes.push(attribute);
            
            // 创建从实体到属性的连接
            links.push({
                from: currentEntity.key,
                to: attribute.key
            });
        }
    });

    return { nodes, links };
}

// 生成图表
function generateDiagram() {
    const inputText = document.getElementById('inputText').value;
    
    if (!inputText.trim()) {
        showNotification('请输入实体和属性信息！', 'warning');
        return;
    }

    try {
        // 显示加载状态
        const diagramDiv = document.getElementById('myDiagramDiv');
        diagramDiv.classList.add('loading');
        
        const { nodes, links } = parseInput(inputText);
        
        if (nodes.length === 0) {
            showNotification('请检查输入格式！确保实体顶格输入，属性有缩进。', 'error');
            diagramDiv.classList.remove('loading');
            return;
        }

        // 隐藏空状态
        document.getElementById('emptyState').style.display = 'none';

        // 更新图表模型
        myDiagram.model = new go.GraphLinksModel(nodes, links);
        
        // 自动布局
        myDiagram.layoutDiagram(true);
        
        // 适应视图
        setTimeout(() => {
            myDiagram.zoomToFit();
            diagramDiv.classList.remove('loading');
            showNotification('图表生成成功！', 'success');
            // 移除水印
            removeGoJSWatermark();
        }, 100);
        
    } catch (error) {
        console.error('生成图表时出错:', error);
        document.getElementById('myDiagramDiv').classList.remove('loading');
        showNotification('生成图表时出错，请检查输入格式！', 'error');
    }
}

// 更新状态信息
function updateStatusInfo() {
    if (!myDiagram) return;
    
    const nodeCount = myDiagram.nodes.count;
    const linkCount = myDiagram.links.count;
    
    document.getElementById('nodeCount').textContent = `节点: ${nodeCount}`;
    document.getElementById('linkCount').textContent = `连接: ${linkCount}`;
}

// 更新字符计数
function updateCharCount() {
    const inputText = document.getElementById('inputText');
    const charCount = document.getElementById('charCount');
    charCount.textContent = inputText.value.length;
}

// 清空输入
function clearInput() {
    document.getElementById('inputText').value = '';
    updateCharCount();
    
    // 显示空状态
    document.getElementById('emptyState').style.display = 'block';
    myDiagram.model = new go.GraphLinksModel([], []);
    updateStatusInfo();
}

// 加载示例
function loadExample() {
    const exampleText = `学生
  学号
  姓名
  年级
  专业
  性别

教师
  工号
  姓名
  职称
  部门
  联系方式

课程
  课程号
  课程名
  学分
  学时
  先修课程`;
    
    document.getElementById('inputText').value = exampleText;
    updateCharCount();
    generateDiagram();
}

// 图表控制功能
function zoomIn() {
    myDiagram.commandHandler.increaseZoom();
}

function zoomOut() {
    myDiagram.commandHandler.decreaseZoom();
}

function zoomToFit() {
    myDiagram.zoomToFit();
}

function centerDiagram() {
    myDiagram.centerRect(myDiagram.documentBounds);
}

// 显示通知
function showNotification(message, type = 'info') {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    notification.innerHTML = `
        <i class="fas ${getNotificationIcon(type)}"></i>
        <span>${message}</span>
    `;
    
    // 添加到页面
    document.body.appendChild(notification);
    
    // 显示动画
    setTimeout(() => {
        notification.classList.add('show');
    }, 100);
    
    // 自动隐藏
    setTimeout(() => {
        notification.classList.remove('show');
        setTimeout(() => {
            document.body.removeChild(notification);
        }, 300);
    }, 3000);
}

function getNotificationIcon(type) {
    switch (type) {
        case 'success': return 'fa-check-circle';
        case 'error': return 'fa-exclamation-circle';
        case 'warning': return 'fa-exclamation-triangle';
        default: return 'fa-info-circle';
    }
}

// 页面加载完成后初始化
document.addEventListener('DOMContentLoaded', function() {
    init();
    
    // 绑定事件
    document.getElementById('generateBtn').addEventListener('click', generateDiagram);
    document.getElementById('clearBtn').addEventListener('click', clearInput);
    document.getElementById('exampleBtn').addEventListener('click', loadExample);
    document.getElementById('zoomInBtn').addEventListener('click', zoomIn);
    document.getElementById('zoomOutBtn').addEventListener('click', zoomOut);
    document.getElementById('fitBtn').addEventListener('click', zoomToFit);
    document.getElementById('centerBtn').addEventListener('click', centerDiagram);
    
    // 输入框事件
    const inputText = document.getElementById('inputText');
    inputText.addEventListener('input', updateCharCount);
    inputText.addEventListener('keydown', function(e) {
        if (e.ctrlKey && e.key === 'Enter') {
            generateDiagram();
        }
    });
    
    // 初始化字符计数
    updateCharCount();
    
    // 设置默认示例
    loadExample();
});

// 窗口大小改变时重新调整图表
window.addEventListener('resize', function() {
    if (myDiagram) {
        myDiagram.requestUpdate();
    }
});

// 添加通知样式到页面
const notificationStyles = `
<style>
.notification {
    position: fixed;
    top: 80px;
    right: 24px;
    display: flex;
    align-items: center;
    gap: 12px;
    padding: 12px 20px;
    border-radius: 8px;
    color: white;
    font-weight: 500;
    box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1);
    transform: translateX(100%);
    transition: transform 0.3s ease;
    z-index: 1000;
}

.notification.show {
    transform: translateX(0);
}

.notification-success {
    background: #10b981;
}

.notification-error {
    background: #ef4444;
}

.notification-warning {
    background: #f59e0b;
}

.notification-info {
    background: #06b6d4;
}
</style>
`;

document.head.insertAdjacentHTML('beforeend', notificationStyles);